package org.xxpay.pay.channel.alizftpay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xxpay.apibase.util.AmountKit;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MyBase64;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayAlizftMchInfo;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.PayConfig;
import org.xxpay.pay.service.CommonService;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Controller
public class AlizftpayController extends BaseApiService {

    private static final MyLog _log = MyLog.getLog(AlizftpayController.class);

    @Autowired
    private CommonService commonService;

    @Autowired
    private PayConfig payConfig;

    @RequestMapping("/api/alizftpay/gateway.htm")
    @ResponseBody
    public String gateway(HttpServletRequest request) {

        JSONObject params = getJsonParam(request);
        if(params.isEmpty()){
            return null;
        }

        _log.info("接收直付通回调信息： params={}", params.toJSONString());

        //审核拒绝
        if("ant.merchant.expand.indirect.zft.rejected".equalsIgnoreCase(params.getString("msg_method"))){

            JSONObject bizContent = JSONObject.parseObject(params.getString("biz_content"));
            String reason = bizContent.getString("reason"); //拒绝原因
            String subMchId = bizContent.getString("external_id"); //商户ID
            String orderId = bizContent.getString("order_id"); //发起订单号

            PayAlizftMchInfo updateRecord = new PayAlizftMchInfo();
            updateRecord.setApplyStatus(MchConstant.ALIZFT_MCH_APPLYSTATUS_FAIL);
            updateRecord.setRejectRemark(reason);

            PayAlizftMchInfo condition = new PayAlizftMchInfo();
            condition.setApplyStatus(MchConstant.ALIZFT_MCH_APPLYSTATUS_ING);
            condition.setApplyOrderId(orderId);
            condition.setSubMchId(Long.parseLong(subMchId));

            commonService.payAlizftMchInfoService.updateByCondition(updateRecord, condition, null);

        }else if("ant.merchant.expand.indirect.zft.passed".equalsIgnoreCase(params.getString("msg_method"))){ //审核通过

            JSONObject bizContent = JSONObject.parseObject(params.getString("biz_content"));
            String subMchId = bizContent.getString("external_id"); //商户ID
            String orderId = bizContent.getString("order_id"); //发起订单号
            String smid = bizContent.getString("smid"); //smid 重要！

            PayAlizftMchInfo updateRecord = new PayAlizftMchInfo();
            updateRecord.setApplyStatus(MchConstant.ALIZFT_MCH_APPLYSTATUS_SUCCESS);
            updateRecord.setSmid(smid);

            PayAlizftMchInfo condition = new PayAlizftMchInfo();
            condition.setApplyStatus(MchConstant.ALIZFT_MCH_APPLYSTATUS_ING);
            condition.setApplyOrderId(orderId);
            condition.setSubMchId(Long.parseLong(subMchId));

            commonService.payAlizftMchInfoService.updateByCondition(updateRecord, condition, null);

        }

        return "SUCCESS";
    }

    @RequestMapping("/api/alizftpay/alipay_qr_{param}.htm")
    public String alipayRec(HttpServletRequest request, ModelMap mm, @PathVariable String param) {
        String logPrefix = "【支付宝直付通当面付支付下单】";
        String paramJson = new String(MyBase64.decode(param));
        JSONObject po = JSONObject.parseObject(paramJson);
        String payOrderId = getString(po, "payOrderId");
        String buyerId = request.getParameter("userId");
        if(buyerId == null) {
            _log.error("{}支付宝授权失败", logPrefix);
            mm.put("errMsg","授权失败，请重新下单");
            return "payment/alipay/alipay_qr";
        }

        //获取订单信息
        PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
        DBApplicationConfig config = commonService.sysConfigService.getDBApplicationConfig();

        //系统配置参数

        String notifyUrl = super.getNotifyUrl(PayConstant.CHANNEL_NAME_ALIZFTPAY, config); //异步回调通知地址
        String returnUrl = super.getReturnUrl(PayConstant.CHANNEL_NAME_ALIZFTPAY, config); //同步跳转地址

        String certRootPath = payConfig.getCertRootPath(); //存放证书的根目录

        //封装请求参数

        AlizftpayConfig alizftpayConfig = new AlizftpayConfig(getPayParam(payOrder));

        AlipayTradeCreateRequest alipayRequest = new AlipayTradeCreateRequest();
        AlipayTradeCreateModel model = new AlipayTradeCreateModel();
        model.setOutTradeNo(payOrderId);
        model.setSubject(payOrder.getSubject());
        model.setTotalAmount(AmountKit.convertCent2Dollar(payOrder.getAmount().toString()));
        model.setBody(payOrder.getBody());

        model.setBuyerId(buyerId); //支付宝UserId

        //传入二级商户ID
        SubMerchant subMerchant = new SubMerchant();
        subMerchant.setMerchantId(payOrder.getChannelSMId());   //进件的SMID 二级商户信息，进件分配给平台商的 smid(ip_role_id)
        model.setSubMerchant(subMerchant);

        //传入结算信息
        SettleInfo settleInfo = new SettleInfo();
        SettleDetailInfo settleDetailInfo = new SettleDetailInfo();
        settleDetailInfo.setAmount(model.getTotalAmount());  //全部金额
        settleDetailInfo.setTransInType("defaultSettle");  //进件默认分账用户
        settleInfo.setSettleDetailInfos(Arrays.asList(settleDetailInfo));
        model.setSettleInfo(settleInfo);

        // 设置花呗分期
        // hb_fq_num 代表花呗分期数，仅支持传入3、6、12，其他期数暂不支持，传入会报错。
        // hb_fq_seller_percent 代表卖家承担收费比例，商家承担手续费传入 100，用户承担手续费传入 0，仅支持传入 100、0 两种，其他比例暂不支持，传入会报错。
        ExtendParams extendParams = new ExtendParams();
        extendParams.setHbFqNum("12");
        extendParams.setHbFqSellerPercent("0");
        // 暂未开启
        //model.setExtendParams(extendParams);


        alipayRequest.setBizModel(model);

        // 设置异步通知地址
        alipayRequest.setNotifyUrl(notifyUrl);
        // 设置同步跳转地址
        alipayRequest.setReturnUrl(returnUrl);

        try {
            AlipayTradeCreateResponse response = alipayExecute(alizftpayConfig, alipayRequest);
            if(! response.isSuccess()){
                _log.error("调起支付宝直付通返回失败！, subMsg={}", response.getSubMsg());
                mm.put("errMsg", "调起支付宝直付通返回失败！");
                return "payment/alipay/alipay_qr";
            }
            //上游订单号
            String channelPayOrderId = response.getTradeNo();
            int updateCount = commonService.payOrderService.updateStatus4Ing(payOrderId, channelPayOrderId);
            _log.info("[{}]更新订单状态为支付中:payOrderId={},result={}", logPrefix, payOrderId, updateCount);
            mm.put("tradeNo", channelPayOrderId);
            return "payment/alipay/alipay_qr";
        } catch (AlipayApiException e) {
            _log.error("", e);
            mm.put("errMsg", "下单失败[" + e.getErrMsg() + "]");
            return "payment/alipay/alipay_qr";
        } catch (Exception e) {
            _log.error("", e);
            mm.put("errMsg", "下单失败[调取通道异常]");
            return "payment/alipay/alipay_qr";
        }

    }

}
